import requests
from email.mime.text import MIMEText
from email.header import Header
import smtplib
import threading
import time
import hashlib


# 邮件发送配置
smtp_host = 'smtp.example.com'
smtp_port = 587
smtp_user = 'your_email@example.com'
smtp_password = 'your_email_password'
receiver = 'receiver_email@example.com'

# 网站列表
websites = {
    '通用-足迹': {'token': '', 'host': 'https://apigw.hkitcloud.net/prod', 'username':'HKLOGINDETDK.com@DK.com', 'pwd':'123', 'url':'https://identity-zj.hkitcloud.net/connect/token'},
    '通用-唯尚': {'token': '', 'host': 'https://apigw.hkitcloud.net/prod', 'username':'HKLOGINDET@ws.com', 'pwd':'123', 'url':'https://identity-zj.hkitcloud.net/connect/token'},
    'GCP-织创': {'token': '', 'host': 'https://tw-gw.hkitcloud.net/prod', 'username':'HKLOGINDET@KYC.com', 'pwd':'123', 'url':'https://gcp-identity.hkitcloud.net/connect/token'}
}

# 探测存放与否的接口列表
api_list = [
    '/basicdata/api/services/app/OuManagement/GetWithCurrentUser',
    '/basicdata/api/services/app/HomeManagement/GetHomeCompanyDetails'
]

def send_email(subject, body):
    message = MIMEText(body, 'plain', 'utf-8')
    message['From'] = Header("Monitoring Script", 'utf-8')
    message['To'] = Header("Receiver", 'utf-8')
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtpObj = smtplib.SMTP(smtp_host, smtp_port)
        smtpObj.starttls()
        smtpObj.login(smtp_user, smtp_password)
        smtpObj.sendmail(smtp_user, receiver, message.as_string())
        print("Email sent successfully")
    except smtplib.SMTPException as e:
        print("Error sending email", e)

def check_login(costumer):
    retries = 0
    max_retries = 3
    # 登录信息
    username = websites[costumer]['username']
    pwd = websites[costumer]['pwd']
    password = hashlib.md5(pwd.encode(encoding='UTF-8')).hexdigest()
    url = websites[costumer]['url']
    # print(username, password)
    while retries < max_retries:
        # 设置请求头
        headers = {

            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0'
        }
        response = requests.post(url, headers=headers, data={'username': username, 'password': password, 'client_secret': 'ClientKey', 'grant_type': 'password', 'client_id': 'HKERP2.0'})
        if response.status_code == 200:
            # 解析响应获取Token
            token = response.json().get('access_token')
            if token:
                # 更新API接口信息中的Token
                websites[costumer]['token'] = token
                print(f"登录成功: {costumer}")
                break  # 登录成功并获取Token后，退出循环
            else:
                print(f"Failed to obtain Token for {url}")
                retries += 1  # 增加重试次数
                # 等待一段时间再尝试，以避免频繁请求
                time.sleep(3)
        else:
            print(f"Login failed for {costumer}")
            retries += 1  # 增加重试次数
            # 等待一段时间再尝试，以避免频繁请求
            print(response.status_code)
            print(response.text)
            time.sleep(3)

    if retries >= max_retries:
        # send_email(f"Login Failed for {url} after 3 attempts", "The login to the website has failed after 3 attempts. Please check the credentials and site status.")
        print(f"Login failed for {costumer} after 3 attempts")
        return

    # 使用Token访问API
    for detect_url in api_list:
        detect_url = websites[costumer]['host'] + detect_url
        response = requests.get(detect_url, headers={'Authorization': f'Bearer {token}'})
        if response.status_code == 200:
            print(f"API call successful for {url}")
            # print(response.json())
        else:
            # send_email(f"API call Failed for {url}", "The API call to the website has failed. Please check the credentials and site status.")
            print(f"API call failed for {url}")


if __name__ == '__main__':
    # 创建线程并启动
    threads = []
    for costumer in websites:
        thread = threading.Thread(target=check_login, args=(costumer,))
        threads.append(thread)
        thread.start()

    # 等待所有线程完成
    for thread in threads:
        thread.join()

    print("All checks completed.")
